import { Tabs, TabsProps } from 'antd';
import React, { useState } from 'react';
import PagesHeader from '@/components/pages-header';

import metahumanService from '@/api/services/metahumanService';
import MetahumanUsage from './components/metahuman-usage';
import MetahumanPermission from './components/metahuman-permission';
import { useRequest } from 'ahooks';
import { TabKeys } from '@/types/metahuman';
import TipDesc from '@/components/tipDesc/tipDesc';


const index = () => {
  const [permissionFlag, setPermissionFlag] = useState(false);

  const tabsItems: TabsProps['items'] = [
    {
      key: TabKeys.USAGE,
      label: <div className="text-sm">数字人使用情况</div>,
    },
    {
      key: TabKeys.PERMISSION,
      label: <div className="text-sm">数字人使用权限</div>,
    },
  ];

  const [tabsValue, setTabsValue] = useState<TabKeys>(TabKeys.USAGE);

  // 更新全局数字人权限配置
  const { runAsync: updateGlobalPermission } = useRequest(
    async (metahumanEnabled: boolean) => {
      const response = await metahumanService.updateMetahumanGlobalPermission({
        metahumanEnabled
      });
      return response;
    },
    {
      manual: true, // 手动触发，不自动执行
      onSuccess: () => {
        setPermissionFlag(!permissionFlag);
      },
      onError: (error) => {
        setPermissionFlag(permissionFlag);
        console.error('更新全局数字人权限配置失败:', error);
      }
    }
  );

  // 获取全局数字人权限状态
  useRequest(
    async () => {
      const response = await metahumanService.getMetahumanGlobalPermissionStatus();
      return response;
    },
    {
      onSuccess: (data) => {
        setPermissionFlag(data.metahumanGlobalEnabled);
      },
      onError: (error) => {
        console.error('获取全局数字人权限状态失败:', error);
      }
    }
  );

  const jumpToPermission = () => {
    setTabsValue(TabKeys.PERMISSION);
  };

  return (
    <div className="flex h-full w-full flex-col rounded-default ">
      <PagesHeader>
        数字人管理
        <TipDesc title='用于管理与智能体绑定的虚拟数字人形象' />
      </PagesHeader>
      <div className="flex flex-1 flex-col px-5">
        <Tabs items={tabsItems} activeKey={tabsValue} onChange={(key) => setTabsValue(key as TabKeys)} />
        {tabsValue === TabKeys.USAGE ?
          <MetahumanUsage
            permissionFlag={permissionFlag}
            jumpToPermission={jumpToPermission}
          />
          :
          <MetahumanPermission permissionFlag={permissionFlag} updateGlobalPermission={updateGlobalPermission} />
        }
      </div>
    </div>
  );
};

export default index;
